<template>
  <div class="chat-container" :class="`theme-${currentTheme}`">
    <particle-background :theme="currentTheme" :particle-count="40" />
    
    <div class="chat-header">
      <router-link to="/" class="back-btn">
        <span>&larr;</span> 返回
      </router-link>
      <h1>AI 超级智能体</h1>
      <button class="theme-toggle" @click="showThemeSelector = !showThemeSelector">
        <span class="theme-icon">🎨</span>
      </button>
      <div class="connection-status" :class="{ connected: isConnected }">
        {{ isConnected ? '已连接' : '未连接' }}
      </div>
    </div>
    
    <div class="theme-selector-container" v-if="showThemeSelector">
      <div class="theme-selector">
        <theme-switcher 
          :themes="availableThemes" 
          :active-theme="currentTheme" 
          @change-theme="changeTheme"
        />
      </div>
    </div>
    
    <div class="messages-container" ref="messagesContainer">
      <div v-if="messages.length === 0" class="welcome-message">
        <h3>欢迎使用AI超级智能体</h3>
        <p>您的智能助手已准备就绪，可以回答各类问题，提供专业知识和生活建议。</p>
        <div class="suggestion-list">
          <div class="suggestion-title">您可以尝试询问：</div>
          <div class="suggestion-item" @click="useExample('如何使用Python处理Excel文件？')">如何使用Python处理Excel文件？</div>
          <div class="suggestion-item" @click="useExample('帮我写一个简单的网页HTML代码')">帮我写一个简单的网页HTML代码</div>
          <div class="suggestion-item" @click="useExample('人工智能未来的发展趋势是什么？')">人工智能未来的发展趋势是什么？</div>
        </div>
      </div>
      
      <chat-message
        v-for="(message, index) in messages"
        :key="index"
        :content="message.content"
        :is-user="message.isUser"
        :is-system-message="message.isSystemMessage"
        :timestamp="message.timestamp || Date.now()"
        avatar-type="superagent"
      />
    </div>
    
    <chat-input 
      :is-loading="loading" 
      @send="sendMessage"
    />
  </div>
</template>

<script>
import ChatMessage from '../components/ChatMessage.vue'
import ChatInput from '../components/ChatInput.vue'
import ParticleBackground from '../components/ParticleBackground.vue'
import ThemeSwitcher from '../components/ThemeSwitcher.vue'
import { createSuperAgentChat } from '../api'

export default {
  name: 'SuperAgentView',
  components: {
    ChatMessage,
    ChatInput,
    ParticleBackground,
    ThemeSwitcher
  },
  data() {
    return {
      messages: [],
      loading: false,
      heartbeatInterval: null,
      eventSource: null,
      lastMessage: '',
      lastAIResponse: '',
      isConnected: false,
      showThemeSelector: false,
      currentTheme: 'blue',
      requestInProgress: false,
      availableThemes: [
        {
          id: 'blue',
          name: '深蓝代码',
          colors: {
            primary: '#1e88e5',
            secondary: '#3949ab'
          }
        },
        {
          id: 'dark',
          name: '暗黑模式',
          colors: {
            primary: '#263238',
            secondary: '#37474f'
          }
        },
        {
          id: 'green',
          name: '翠绿终端',
          colors: {
            primary: '#43a047',
            secondary: '#2e7d32'
          }
        },
        {
          id: 'purple',
          name: '紫色科技',
          colors: {
            primary: '#9c27b0',
            secondary: '#6a1b9a'
          }
        }
      ]
    }
  },
  created() {
    // 尝试从localStorage加载主题设置
    const savedTheme = localStorage.getItem('superAgentTheme');
    if (savedTheme && this.availableThemes.some(theme => theme.id === savedTheme)) {
      this.currentTheme = savedTheme;
    }
    
    // 添加一条欢迎消息
    this.messages.push({
      content: '您好！有什么我可以帮助您的吗？',
      isUser: false,
      timestamp: Date.now()
    })

    // 设置页面标题
    document.title = 'AI超级智能体 - 全能AI助手';
    
    // 检查URL查询参数是否包含问题，如果有则自动发送
    const queryQuestion = this.$route.query.q;
    if (queryQuestion) {
      // 使用setTimeout确保组件完全挂载后再发送消息
      setTimeout(() => {
        this.sendMessage(queryQuestion);
      }, 1000);
    }
  },
  methods: {
    // 发送消息到后端
    sendMessage(message) {
      console.log('发送消息:', message)
      
      // 如果已经有一个请求正在进行中，则忽略新的请求
      if (this.requestInProgress) {
        console.log('请求正在处理中，忽略新请求')
        return
      }
      
      // 设置请求处理中状态
      this.requestInProgress = true
      
      // 重置最后一次AI响应
      this.lastAIResponse = ''
      
      // 保存最后发送的消息
      this.lastMessage = message
      
      // 添加用户消息到聊天记录
      this.messages.push({
        content: message,
        isUser: true,
        timestamp: Date.now()
      })
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
      
      this.loading = true
      
      // 清理之前的所有连接和资源
      this.cleanupConnection()
      
      if (this.heartbeatInterval) {
        clearInterval(this.heartbeatInterval)
        this.heartbeatInterval = null
      }
      
      // 创建新的SSE连接
      console.log('创建新的SSE连接')
      this.eventSource = createSuperAgentChat(message)
      
      if (!this.eventSource) {
        console.error('创建SSE连接失败')
        this.loading = false
        this.requestInProgress = false
        return
      }
      
      // 设置事件监听器
      this.setupEventListeners()
    },
    
    // 判断是否为应该过滤的系统状态消息
    isSystemStatusMessage(message) {
      // 定义需要过滤的关键词
      const filterKeywords = [
        '执行结束',
        '达到最大步骤',
        '步骤限制',
        '执行完成',
        '任务结束',
        'Execution complete',
        'Max steps reached',
        'Task finished'
      ]
      
      // 检查消息是否包含任何需要过滤的关键词
      for (const keyword of filterKeywords) {
        if (message.includes(keyword)) {
          return true
        }
      }
      
      return false
    },
    
    // 设置SSE事件监听器
    setupEventListeners() {
      // 处理返回的消息流
      this.eventSource.onmessage = (event) => {
        try {
          const response = event.data
          if (!response || response.trim() === '') return
          
          console.log(`收到消息:`, response.substring(0, 30) + '...')
          
          // 检查是否为系统状态消息，如果是则不显示
          if (this.isSystemStatusMessage(response)) {
            console.log('过滤系统状态消息:', response)
            return
          }
          
          // 检查当前响应是否与最后一次相同，如果相同则不显示
          if (response !== this.lastAIResponse) {
            // 更新最后一次响应
            this.lastAIResponse = response
            
            // 为每个不重复的响应单独创建一个消息气泡
            this.messages.push({
              content: response,
              isUser: false,
              timestamp: Date.now()
            })
            
            // 检查用户是否在底部，仅当用户在底部时自动滚动
            this.$nextTick(() => {
              const container = this.$refs.messagesContainer
              if (container) {
                // 检查是否在底部或接近底部
                const isAtBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 100
                if (isAtBottom) {
                  this.scrollToBottom()
                }
              }
            })
          } else {
            console.log('过滤重复消息:', response.substring(0, 30) + '...')
          }
        } catch (error) {
          console.error(`处理消息时出错:`, error)
        }
      }
      
      // 连接打开时的处理
      this.eventSource.onopen = (event) => {
        console.log(`SSE连接已打开`)
        this.isConnected = true
      }
      
      // 错误处理
      this.eventSource.onerror = (error) => {
        console.error(`SSE连接错误:`, error)
        
        // 只记录错误并关闭连接，不添加系统消息
        this.cleanupConnection()
      }
      
      // 添加end事件处理
      this.eventSource.addEventListener('end', () => {
        console.log(`SSE连接结束`)
        this.cleanupConnection()
      })
    },
    
    // 滚动到底部
    scrollToBottom() {
      const container = this.$refs.messagesContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    
    // 使用示例问题
    useExample(example) {
      this.sendMessage(example)
    },
    
    // 清理连接相关资源
    cleanupConnection() {
      if (this.eventSource) {
        // 移除所有事件监听器
        this.eventSource.onmessage = null
        this.eventSource.onerror = null
        this.eventSource.onopen = null
        
        // 关闭连接
        this.eventSource.close()
        this.eventSource = null
      }
      
      this.loading = false
      this.isConnected = false
      this.requestInProgress = false
    },
    
    // 切换主题
    changeTheme(themeId) {
      this.currentTheme = themeId;
      localStorage.setItem('superAgentTheme', themeId);
      
      // 延迟隐藏主题选择器
      setTimeout(() => {
        this.showThemeSelector = false;
      }, 300);
    }
  },
  beforeUnmount() {
    console.log('组件卸载，清理资源')
    
    // 组件销毁前清理所有连接和定时器
    this.cleanupConnection()
    
    if (this.heartbeatInterval) {
      clearInterval(this.heartbeatInterval)
      this.heartbeatInterval = null
    }
  }
}
</script>

<style scoped>
.chat-container {
  height: 100vh;
  background-color: var(--bg-color, #f5f7fa);
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

.chat-container.theme-blue {
  --primary-color: #1e88e5;
  --secondary-color: #3949ab;
  --bg-color: #f5f7fa;
  --gradient: linear-gradient(to right, #3949ab, #1e88e5);
  --text-color: #333;
}

.chat-container.theme-dark {
  --primary-color: #263238;
  --secondary-color: #455a64;
  --bg-color: #121212;
  --gradient: linear-gradient(to right, #263238, #37474f);
  --text-color: #e0e0e0;
}

.chat-container.theme-green {
  --primary-color: #43a047;
  --secondary-color: #2e7d32;
  --bg-color: #f1f8e9;
  --gradient: linear-gradient(to right, #2e7d32, #43a047);
  --text-color: #333;
}

.chat-container.theme-purple {
  --primary-color: #9c27b0;
  --secondary-color: #6a1b9a;
  --bg-color: #f3e5f5;
  --gradient: linear-gradient(to right, #6a1b9a, #9c27b0);
  --text-color: #333;
}

.chat-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 25% 25%, rgba(30, 136, 229, 0.03) 0%, transparent 50%),
    radial-gradient(circle at 75% 75%, rgba(57, 73, 171, 0.03) 0%, transparent 50%);
  z-index: 0;
}

.chat-header {
  padding: 15px 20px;
  background-color: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 1px 10px rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 10;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  color: var(--text-color, #333);
}

.theme-dark .chat-header {
  background-color: rgba(0, 0, 0, 0.2);
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.chat-header h1 {
  margin: 0;
  font-size: 1.3rem;
  color: var(--primary-color, #1e88e5);
  text-align: center;
  flex-grow: 1;
  font-weight: 600;
}

.back-btn {
  display: flex;
  align-items: center;
  color: var(--text-color, #333);
  text-decoration: none;
  font-size: 0.95rem;
  font-weight: 500;
  transition: opacity 0.2s;
}

.theme-dark .back-btn {
  color: rgba(255, 255, 255, 0.9);
}

.back-btn:hover {
  opacity: 0.8;
}

.back-btn span {
  margin-right: 5px;
  font-size: 1.2rem;
}

.theme-toggle {
  background: none;
  border: none;
  color: var(--primary-color, #1e88e5);
  font-size: 1.2rem;
  cursor: pointer;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.2s;
  margin-right: 10px;
}

.theme-dark .theme-toggle {
  color: rgba(255, 255, 255, 0.9);
}

.theme-toggle:hover {
  background-color: rgba(0, 0, 0, 0.05);
}

.theme-dark .theme-toggle:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.theme-icon {
  font-size: 16px;
}

.theme-selector-container {
  position: fixed;
  top: 70px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  z-index: 100;
  padding: 0 20px;
  animation: slideDown 0.3s ease-out forwards;
  pointer-events: none;
}

.theme-selector {
  pointer-events: auto;
  animation: fadeInDown 0.4s;
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideDown {
  from {
    transform: translateY(-10px);
  }
  to {
    transform: translateY(0);
  }
}

.connection-status {
  font-size: 12px;
  padding: 4px 12px;
  border-radius: 20px;
  display: flex;
  align-items: center;
  background: rgba(244, 67, 54, 0.1);
  color: #f44336;
}

.connection-status::before {
  content: '';
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #f44336;
  margin-right: 6px;
  display: inline-block;
}

.connection-status.connected {
  background: rgba(76, 175, 80, 0.1);
  color: #4caf50;
}

.connection-status.connected::before {
  background-color: #4caf50;
}

.theme-dark .connection-status {
  background: rgba(244, 67, 54, 0.2);
}

.theme-dark .connection-status.connected {
  background: rgba(76, 175, 80, 0.2);
}

.messages-container {
  flex-grow: 1;
  overflow-y: auto;
  padding: 20px;
  scroll-behavior: smooth;
  position: relative;
  z-index: 1;
  background: transparent;
}

.welcome-message {
  text-align: center;
  margin: 40px auto;
  color: #333;
  padding: 24px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  max-width: 500px;
  animation: fadeIn 0.6s ease-out;
  border: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.welcome-message::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: var(--gradient, linear-gradient(to right, #3949ab, #1e88e5));
}

.welcome-message h3 {
  margin-bottom: 12px;
  color: var(--primary-color, #3949ab);
  font-weight: 600;
  font-size: 20px;
}

.welcome-message p {
  margin-bottom: 0;
  line-height: 1.6;
  color: #555;
  font-size: 15px;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.suggestion-list {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.suggestion-title {
  font-size: 15px;
  color: #555;
  margin-bottom: 6px;
  font-weight: 500;
}

.suggestion-item {
  background: linear-gradient(to right, rgba(255, 255, 255, 0.9), rgba(232, 240, 254, 0.9));
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  padding: 12px 18px 12px 42px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  color: var(--primary-color, #1e88e5);
  width: 100%;
  text-align: left;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  position: relative;
}

.theme-dark .suggestion-item {
  background: linear-gradient(to right, rgba(40, 44, 52, 0.9), rgba(33, 37, 43, 0.9));
  border: 1px solid #333;
  color: rgba(255, 255, 255, 0.9);
}

.suggestion-item::before {
  content: '❓';
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 16px;
  color: var(--primary-color, #3949ab);
}

.theme-dark .suggestion-item::before {
  color: var(--primary-color, #1e88e5);
}

.suggestion-item:hover {
  background-color: #e3f2fd;
  border-color: rgba(30, 136, 229, 0.2);
  transform: translateY(-2px);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
}

.theme-dark .suggestion-item:hover {
  background-color: rgba(30, 136, 229, 0.1);
  border-color: rgba(30, 136, 229, 0.3);
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background: rgba(30, 136, 229, 0.2);
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: rgba(30, 136, 229, 0.4);
}

.theme-dark .messages-container::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.1);
}

.theme-dark .messages-container::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.2);
}

/* 响应式样式 */
@media (max-width: 767px) {
  .chat-header {
    padding: 12px 16px;
  }
  
  .chat-header h1 {
    font-size: 16px;
  }
  
  .back-btn {
    margin-right: 8px;
    padding: 4px;
  }
  
  .messages-container {
    padding: 16px;
  }
  
  .connection-status {
    padding: 4px 10px;
    font-size: 10px;
  }
  
  .connection-status::before {
    width: 6px;
    height: 6px;
    margin-right: 5px;
  }
  
  .welcome-message {
    padding: 20px;
    margin: 20px 0;
  }
  
  .suggestion-item {
    padding: 10px 14px 10px 36px;
    font-size: 13px;
  }
  
  .suggestion-item::before {
    left: 12px;
    font-size: 14px;
  }
  
  .theme-toggle {
    width: 28px;
    height: 28px;
    margin-right: 8px;
  }
  
  .theme-icon {
    font-size: 14px;
  }
}

.message-bubble.system-message {
  background-color: rgba(244, 67, 54, 0.1);
  border: 1px solid rgba(244, 67, 54, 0.3);
  color: #d32f2f;
  font-weight: 500;
  text-align: center;
  max-width: 80%;
  margin: 10px auto;
  padding: 10px 16px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(244, 67, 54, 0.1);
}

.theme-dark .message-bubble.system-message {
  background-color: rgba(244, 67, 54, 0.2);
  border: 1px solid rgba(244, 67, 54, 0.3);
  color: #ff5252;
}

/* 动画效果 */
.animate-fade-in {
  animation: fadeIn 0.6s ease-out forwards;
  opacity: 0;
}

.animate-fade-in-delayed {
  animation: fadeIn 0.8s ease-out forwards;
  opacity: 0;
}

.animate-slide-in {
  animation: slideInRight 0.5s ease-out forwards;
  opacity: 0;
  transform: translateX(20px);
}

.message-animate-enter-active {
  animation: scaleUp 0.3s ease-out forwards;
}

.message-animate-leave-active {
  animation: fadeOut 0.2s ease-in forwards;
}

.message-animate-move {
  transition: transform 0.5s;
}

/* 打字机效果 */
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes fadeOut {
  from { opacity: 1; }
  to { opacity: 0; }
}

@keyframes slideInRight {
  from { transform: translateX(20px); opacity: 0; }
  to { transform: translateX(0); opacity: 1; }
}

@keyframes scaleUp {
  from { transform: scale(0.95); opacity: 0; }
  to { transform: scale(1); opacity: 1; }
}
</style> 